package com.linglingC.service.serviceImpl;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.linglingC.mapper.UserMapper;
import com.linglingC.pojo.User;
import com.linglingC.service.UserService;
import com.linglingC.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User login(String account, String password) {

        return userMapper.login(account,password);
    }

    @Override
    public User getUser(String account) {
        User user=userMapper.getUser(account);
        return user;
    }

    @Override
    public void uploadImage(MultipartFile image) throws IOException {
        String fileName= UUID.randomUUID().toString();
        image.transferTo(new File("D:/AllTest/contest/contest/src/assets/"+ fileName+".jpg"));
        updateTime();
        userMapper.uploadImage(fileName);
    }

    @Override
    public void updateTime() {
        LocalDateTime time=LocalDateTime.now();
        userMapper.updateTime(time);
    }

    @Override
    public void updatePassword(String password,HttpServletRequest request) {
        String token=request.getHeader("token");
        Claims jwt=  JwtUtils.parseJWT(token);
        String account=jwt.get("account",String.class);
        userMapper.updatePassword(password,account);
        updateTime();
    }

    @Override
    public User updateName(String name, HttpServletRequest request) {
        String token=request.getHeader("token");
        Claims jwt=  JwtUtils.parseJWT(token);
        String account=jwt.get("account",String.class);
        userMapper.updateName(name,account);

        User user=userMapper.getUser(account);
        updateTime();

        return user;
    }


}

